package com.relytosoft.mizar.media.host.emqx;

import cn.hutool.core.lang.UUID;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.TypeReference;
import com.relytosoft.mizar.media.camera.api.entity.CameraBase;
import com.relytosoft.mizar.media.camera.api.entity.CameraChannel;
import com.relytosoft.mizar.media.camera.api.entity.CameraPlatform;
import com.relytosoft.mizar.media.camera.api.pojo.dto.CameraBaseWithPlatformDto;
import com.relytosoft.mizar.media.camera.services.constant.EncodeDeviceProtocol;
import com.relytosoft.mizar.media.camera.services.service.HkSyncService;
import com.relytosoft.mizar.media.common.constant.MediaMqConstants;
import com.relytosoft.mizar.media.common.emqx.client.MqttOp;
import com.relytosoft.mizar.media.common.utils.AesUtils;
import com.relytosoft.mizar.media.external.api.analyze.request.Device;
import com.relytosoft.mizar.media.external.api.analyze.response.DeviceDto;
import com.relytosoft.mizar.media.external.api.analyze.service.DeviceService;
import com.relytosoft.mizar.media.external.api.camera.request.PageInfo;
import com.relytosoft.mizar.media.external.api.camera.response.ChannelDto;
import com.relytosoft.mizar.media.external.api.camera.response.RegionDeviceDto;
import com.relytosoft.mizar.media.external.api.camera.response.Root;
import com.relytosoft.mizar.media.external.api.camera.service.CameraService;
import com.relytosoft.mizar.media.external.api.camera.service.ChannelService;
import com.relytosoft.mizar.media.system.api.pojo.dto.DistrictFeignDto;
import org.eclipse.paho.client.mqttv3.MqttMessage;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.nio.charset.StandardCharsets;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @author Jierry
 * @version 2022/4/22.
 */
@Component
public class CameraMqttMessageListener implements com.relytosoft.mizar.media.common.emqx.listener.CameraMqttMessageListener {

    private static final Logger log = LoggerFactory.getLogger(CameraMqttMessageListener.class);

    @Resource
    private CameraService cameraService;

    @Resource
    private ChannelService channelService;

    @Resource
    private HkSyncService hkSyncService;

    @Resource
    private DeviceService deviceService;


    @Override
    public void messageArrived(String topic, MqttMessage message) {
        log.info("线程名称：【" + Thread.currentThread().getName() + "】" + "接收的主题：" + topic);
        if (MediaMqConstants.CAMERA_TOPIC.equals(topic)) {
            boolean isConsume = false;
            //获取消息
            String mqttMsg = new String(message.getPayload(), StandardCharsets.UTF_8);
            try {
                //转为json
                JSONObject jsonObject = JSON.parseObject(mqttMsg);
                //获取
                String opType = jsonObject.getString("OpType");
                String data = jsonObject.getString("Data");
                switch (opType) {
                    case "SELECT_HK_ENCODE":
                        isConsume = selectHkEncode(data);
                        break;
                    case "INSERT_OWN_CAMERA":
                        isConsume = insertOwnCamera(data);
                        break;
                    case "SELECT_HK_CHANNEL":
                        isConsume = selectHkChannel(data);
                        break;
                    case "INSERT_OWN_CHANNEL":
                        isConsume = insertOwnChannel(data);
                        break;
                    case "INSERT_BTDL":
                        isConsume = insertCameraToBtdl(data);
                        break;
                    case "INSERT_CAMERAPLATE":
                        isConsume = insertCameraSPlateForm(data);
                        break;
                    case "SELECT_BTDL_DEVICE":
                        isConsume = selectBtdlDevice(data);
                        break;
                    default:
                }
                log.info("线程名称：【" + Thread.currentThread().getName() + "】" + "接收的主题：" + topic + ",接收的操作类型：" + opType + "，执行结果：" + isConsume);
            } catch (Exception e) {
                log.info("线程名称：【" + Thread.currentThread().getName() + "】" + "接收的主题：" + topic + ",处理发生错误：" + e.getMessage());
            }
        }
    }

    /**
     * 查询BTDL设备和自己库中已有BTDL设备,删除BTDL多余设备
     *
     * @param data 数据
     * @return 是否消费
     */
    private boolean selectBtdlDevice(String data) {
        boolean isConsume = false;
        //将data转为List<CameraBaseWithPlatformDto>
        List<CameraBaseWithPlatformDto> cameraBaseWithPlatformDtos = JSONObject.parseObject(data, new TypeReference<List<CameraBaseWithPlatformDto>>() {
        });

        //分页查询比特大陆设备信息
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("size", 1000);
        List<DeviceDto> deviceList = new ArrayList<>();
        for (int i = 1; true; i++) {
            jsonObject.put("page", i);
            List<DeviceDto> btdlDeviceList = deviceService.getDeviceList(jsonObject.toJSONString());
            deviceList.addAll(btdlDeviceList);
            if (btdlDeviceList.size() < 1000) {
                break;
            }
        }

        //获取cameraBaseWithPlatformDtos中platformName为BTDL的platformCameraCode
        List<String> platformCameraCodeList = cameraBaseWithPlatformDtos
                .stream()
                .filter(cameraBaseWithPlatformDto -> "BTDL".equals(cameraBaseWithPlatformDto.getPlatformName()))
                .map(CameraBaseWithPlatformDto::getPlatformCameraCode).collect(Collectors.toList());

        //获取deviceList的deviceId
        List<String> deviceIdList = deviceList.stream().map(DeviceDto::getDeviceId).collect(Collectors.toList());

        // deviceIdList中不存在的deviceId(筛选出BTDL在本系统数据库中不存在的设备)
        List<String> notExistDeviceIdList = platformCameraCodeList.stream().filter(deviceId -> !deviceIdList.contains(deviceId)).collect(Collectors.toList());

        // 删除不存在的deviceId
        if (notExistDeviceIdList.size() > 0) {
            isConsume = deviceService.delDevice(notExistDeviceIdList);
        }

        //MqttOp发送消息同步设备到BTDL
        if (isConsume) {
            JSONObject mqttJson = new JSONObject();
            mqttJson.put("OpType", "INSERT_BTDL");
            mqttJson.put("Data", cameraBaseWithPlatformDtos);
            MqttOp.publish(MediaMqConstants.CAMERA_TOPIC, mqttJson.toJSONString());
        }
        return isConsume;
    }


    /**
     * 添加信息到关联的三方平台数据库
     *
     * @param data 消息接收的数据
     * @return 是否成功
     */
    private boolean insertCameraSPlateForm(String data) {
        //1. 将data转换为List<CameraBaseWithPlatformDto>
        List<CameraBaseWithPlatformDto> cameraBaseWithPlatformDtos = JSONObject.parseObject(data, new TypeReference<List<CameraBaseWithPlatformDto>>() {
        });

        //2. 遍历List<CameraBaseWithPlatformDto>转为List<CameraPlatform>
        List<CameraPlatform> cameraPlatforms = cameraBaseWithPlatformDtos.stream().map(cameraBaseWithPlatformDto -> {
            CameraPlatform cameraPlatform = new CameraPlatform();
            cameraPlatform.setOwnId(cameraBaseWithPlatformDto.getId());
            cameraPlatform.setPlatformCameraCode(cameraBaseWithPlatformDto.getPlatformCameraCode());
            cameraPlatform.setPlatformName("BTDL");
            cameraPlatform.setType(1);
            cameraPlatform.setIsSync(1);
            cameraPlatform.setStatus(1);
            return cameraPlatform;
        }).collect(Collectors.toList());

        //3. 添加信息到关联的三方平台数据库
        return hkSyncService.batchInsertCameraPlatform(cameraPlatforms);
    }

    /**
     * 同步设备到比特大陆
     *
     * @return 是否成功
     */
    private boolean insertCameraToBtdl(String data) {
        //将data转为List<CameraBaseWithPlatformDto>
        List<CameraBaseWithPlatformDto> cameraBaseWithPlatformDtos = JSONObject.parseObject(data, new TypeReference<List<CameraBaseWithPlatformDto>>() {
        });

        //筛选出cameraBaseWithPlatformDtos中platformName为BTDL的数据
        List<CameraBaseWithPlatformDto> btdlCameraBaseWithPlatformDtos = cameraBaseWithPlatformDtos
                .stream()
                .filter(cameraBaseWithPlatformDto -> "BTDL".equals(cameraBaseWithPlatformDto.getPlatformName()))
                .collect(Collectors.toList());

        //筛选出cameraBaseWithPlatformDtos中platformName为HK的数据
        List<CameraBaseWithPlatformDto> hkCameraBaseWithPlatformDtos = cameraBaseWithPlatformDtos
                .stream()
                .filter(cameraBaseWithPlatformDto -> "HK".equals(cameraBaseWithPlatformDto.getPlatformName()))
                .collect(Collectors.toList());

        //筛选出hkCameraBaseWithPlatformDtos中ID在btdlCameraBaseWithPlatformDtos中不存在的数据
        List<CameraBaseWithPlatformDto> notExistBtdlCameraBaseWithPlatformDtos = hkCameraBaseWithPlatformDtos
                .stream()
                .filter(cameraBaseWithPlatformDto -> btdlCameraBaseWithPlatformDtos
                        .stream()
                        .noneMatch(btdlCameraBaseWithPlatformDto -> btdlCameraBaseWithPlatformDto.getId().equals(cameraBaseWithPlatformDto.getId())))
                .collect(Collectors.toList());

        //notExistBtdlCameraBaseWithPlatformDtos为空，直接返回
        if (notExistBtdlCameraBaseWithPlatformDtos.isEmpty()) {
            return true;
        }

        //notExistBtdlCameraBaseWithPlatformDtos转为device
        List<Device> devices = notExistBtdlCameraBaseWithPlatformDtos
                .stream()
                .map(cameraBaseWithPlatformDto -> {
                    Device device = new Device();
                    device.setProtocol(2);  //协议类型
                    device.setUrl(getUrl(cameraBaseWithPlatformDto));   //设备地址
                    device.setName(cameraBaseWithPlatformDto.getName());    //设备名称
                    device.setIpAddr(cameraBaseWithPlatformDto.getIp());    //设备IP
                    device.setPort(cameraBaseWithPlatformDto.getPort());    //设备端口
                    device.setUser(AesUtils.aesDeCode(cameraBaseWithPlatformDto.getUserName()));    //设备用户名
                    device.setPass(AesUtils.aesDeCode(cameraBaseWithPlatformDto.getPassword()));    //设备密码
                    return device;
                }).collect(Collectors.toList());

        //循环调用deviceService中addDevice方法添加devices到比特大陆,并将比特大陆返回的DeviceDto中的deviceId更新到notExistBtdlCameraBaseWithPlatformDtos中的platformCameraCode中
        for (Device device : devices) {
            DeviceDto deviceDto = deviceService.addDevice(device);
            if (deviceDto != null) {
                for (CameraBaseWithPlatformDto cameraBaseWithPlatformDto : notExistBtdlCameraBaseWithPlatformDtos) {
                    if (deviceDto.getDeviceId().equals(cameraBaseWithPlatformDto.getPlatformCameraCode())) {
                        cameraBaseWithPlatformDto.setPlatformCameraCode(deviceDto.getDeviceId());
                    }
                }
            }
        }
        //创建JSONObject对象,键为Data值为notExistBtdlCameraBaseWithPlatformDtos和键为OpType值为INSERT_CAMERAPLATE的JSONObject对象，MqttOp.publish方法发送消息到主题MediaMqConstants.CAMERA_TOPIC
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("OpType", "INSERT_CAMERAPLATE");
        jsonObject.put("Data", notExistBtdlCameraBaseWithPlatformDtos);
        MqttOp.publish(MediaMqConstants.CAMERA_TOPIC, jsonObject.toJSONString());
        return true;
    }

    private String getUrl(CameraBaseWithPlatformDto cameraBaseWithPlatformDto) {
        String url = "rtsp://%s:%s@%s:554";
        String userName = AesUtils.aesDeCode(cameraBaseWithPlatformDto.getUserName());
        String password = AesUtils.aesDeCode(cameraBaseWithPlatformDto.getPassword());
        return String.format(url, userName, password, cameraBaseWithPlatformDto.getIp());
    }

    private boolean insertOwnChannel(String data) {
        boolean isConsume;
        Map<String, String> objectMap = JSONObject.parseObject(data, new TypeReference<Map<String, String>>() {
        });
        //第三方所有通道信息
        List<ChannelDto> channelDtoList = JSON.parseObject(objectMap.get("channel"), new TypeReference<List<ChannelDto>>() {
        });

        //筛选出三方通道的唯一标识
        List<String> channelIndexCodes = channelDtoList.stream().map(ChannelDto::getCameraIndexCode).collect(Collectors.toList());

        //查询本系统所有通道信息
        List<CameraPlatform> selectList = hkSyncService.selectAllPlatformCode(null, 1);
        List<ChannelDto> alreadyThreeData = new ArrayList<>();
        if (!selectList.isEmpty()) {
            List<String> ownChannelIndexCodes = selectList.stream().map(CameraPlatform::getPlatformChannelCode).collect(Collectors.toList());
            channelIndexCodes.removeAll(ownChannelIndexCodes);
            //查询已存在数据库得三方数据
            alreadyThreeData = channelDtoList.stream().filter(item -> ownChannelIndexCodes.contains(item.getCameraIndexCode())).collect(Collectors.toList());

        }

        if (Boolean.parseBoolean(objectMap.get("isUpdate")) && !alreadyThreeData.isEmpty()) {
            //查询出通道信息
            Set<Integer> channelIds = selectList.stream().map(item -> {
                if (item.getType() == 2 && item.getType() != null && item.getStatus() == 1) {
                    return item.getOwnId();
                } else {
                    return null;
                }
            }).filter(Objects::nonNull).collect(Collectors.toSet());
            List<CameraChannel> cameraChannelList = hkSyncService.batchSelectByCameraChannelIds(channelIds);
            //查询
            isConsume = updateCameraChannel(cameraChannelList, alreadyThreeData);
        }

        if (channelIndexCodes.size() > 0) {
            //收集所有需要添加的数据
            List<ChannelDto> needAddData = channelDtoList
                    .stream()
                    .filter(item -> channelIndexCodes.contains(item.getCameraIndexCode()))
                    .collect(Collectors.toList());
            //转换数据
            List<CameraChannel> cameraChannelList = convertCameraChannel(needAddData);

            //获取设备id
            Map<String, Integer> map = selectList
                    .stream()
                    .collect(Collectors.toMap(CameraPlatform::getPlatformCameraCode, CameraPlatform::getOwnId));

            //设置设备id
            cameraChannelList = cameraChannelList.stream()
                    .peek(item -> item.setCameraId(map.get(item.getEncodeDevIndexCode())))
                    .collect(Collectors.toList());

            //过滤没有设备id得通道。没有设备就没有通道
            List<CameraChannel> channelList = cameraChannelList.stream()
                    .filter(cameraChannel -> cameraChannel.getCameraId() != null)
                    .collect(Collectors.toList());

            //批量添加通道信息
            isConsume = hkSyncService.batchInsertCameraChannel(channelList);
            //关联表数据添加
            if (isConsume) {
                List<CameraPlatform> cameraPlatformList = convertToCameraPlatform(channelList);
                isConsume = hkSyncService.batchInsertCameraPlatform(cameraPlatformList);
                if (isConsume) {
                    //更新设备表设备类型
                    //1. 获取设备id
                    Set<Integer> cameraIds = channelList.stream().map(CameraChannel::getCameraId).collect(Collectors.toSet());
                    //获取设备id为key，类型id为value得map
                    Map<Integer, Integer> cameraIdType = channelList.stream().collect(Collectors.toMap(CameraChannel::getCameraId, CameraChannel::getCameraTypeId));
                    //查询出所有通道相关联得得设备
                    List<CameraBase> cameraBaseList = hkSyncService.batchSelectByCameraIds(cameraIds);
                    //根据设备id设置设备类型
                    cameraBaseList.forEach(item -> item.setCameraTypeId(cameraIdType.get(item.getId())));
                    //更新
                    isConsume = hkSyncService.batchUpdateCameraBase(cameraBaseList);
                }
            }
            return isConsume;
        }
        return true;
    }

    private boolean updateCameraChannel(List<CameraChannel> cameraChannelList, List<ChannelDto> alreadyThreeData) {
        for (CameraChannel cameraChannel : cameraChannelList) {
            for (ChannelDto alreadyThreeDatum : alreadyThreeData) {
                if (cameraChannel.getPlatformChannelCode().equals(alreadyThreeDatum.getCameraIndexCode())) {
                    //更新通道编号
                    cameraChannel.setChannelNum(alreadyThreeDatum.getChannelNo());
                    //更新能力集
                    cameraChannel.setCamability(alreadyThreeDatum.getCapabilitySet());
                    //协议类型
                    cameraChannel.setTransType(alreadyThreeDatum.getTransType() == 1 ? 1000 : 1001);
                }
            }
        }
        return hkSyncService.batchUpdateCameraChannel(cameraChannelList);
    }

    private List<CameraPlatform> convertToCameraPlatform(List<CameraChannel> channelList) {
        List<CameraPlatform> cameraPlatformList = new ArrayList<>();
        for (CameraChannel channel : channelList) {
            CameraPlatform cameraPlatform = new CameraPlatform();
            cameraPlatform.setOwnId(channel.getId());
            cameraPlatform.setType(2);
            cameraPlatform.setPlatformName("HK");
            cameraPlatform.setPlatformChannelCode(channel.getPlatformChannelCode());
            cameraPlatform.setIsSync(1);
            cameraPlatform.setStatus(1);
            cameraPlatformList.add(cameraPlatform);
        }
        return cameraPlatformList;
    }


    private List<CameraChannel> convertCameraChannel(List<ChannelDto> channelDtoList) {
        Map<String, Integer> map = hkSyncService.findCameraType();
        //拼接通道数据对象
        List<CameraChannel> cameraChannelList = new ArrayList<>();
        for (ChannelDto channelDTO : channelDtoList) {
            CameraChannel channel = new CameraChannel();
            //通道编码
            channel.setChannelCode(UUID.fastUUID().toString());
            //通道名称
            channel.setChannelName(channelDTO.getCameraName());
            //连接协议
            channel.setTransType(channelDTO.getTransType() == 1 ? 1000 : 1001);
            //摄像机类型
            channel.setCameraTypeId(map.get(channelDTO.getCameraTypeName()));
            //设备能力集
            channel.setCamability(channelDTO.getCapabilitySet());
            //经度
            channel.setLongItude(channelDTO.getLongitude());
            //纬度
            channel.setLatItude(channelDTO.getLatitude());
            //状态
            channel.setStatus(1);
            //通道编号
            channel.setChannelNum(channelDTO.getChannelNo());
            //编码设备唯一码
            channel.setEncodeDevIndexCode(channelDTO.getEncodeDevIndexCode());
            //通道编码
            channel.setPlatformChannelCode(channelDTO.getCameraIndexCode());
            //添加到集合
            cameraChannelList.add(channel);
        }
        return cameraChannelList;
    }


    /**
     * 查询海康数据
     *
     * @return 确认消息是否接收成功
     */
    private boolean selectHkChannel(String data) {
        //获取海康返回数据
        Root<ChannelDto> root = channelService.channelPage(new PageInfo(1L, 1000L));
        //发送添加根区域消息
        HashMap<String, String> map = new HashMap<>(66);
        map.put("channel", JSON.toJSONString(root.getList()));
        map.put("isUpdate", data);
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("OpType", "INSERT_OWN_CHANNEL");
        jsonObject.put("Data", map);
        MqttOp.publish(MediaMqConstants.CAMERA_TOPIC, JSON.toJSONString(jsonObject));
        return true;
    }


    private boolean selectHkEncode(String data) {
        Map<String, String> map = JSON.parseObject(data, new TypeReference<Map<String, String>>() {
        });
        List<DistrictFeignDto> feignDTOList = JSONObject.parseObject(map.get("feignDTOList"), new TypeReference<List<DistrictFeignDto>>() {
        });
        //远程调用查询海康数据
        List<RegionDeviceDto> hkData = new ArrayList<>();
        for (DistrictFeignDto districtFeignDTO : feignDTOList) {
            String platformId = districtFeignDTO.getPlatformId();
            if (!StrUtil.isEmptyIfStr(platformId)) {
                Root<RegionDeviceDto> root = cameraService
                        .regionEncodeDevice(new PageInfo(1L, 1000L, new String[]{"view"}, platformId));
                if (root != null) {
                    hkData.addAll(root.getList());
                }
            }
        }
        Map<String, String> addmMap = new HashMap<>(20);
        addmMap.put("hkData", JSON.toJSONString(hkData));
        addmMap.put("area", JSON.toJSONString(feignDTOList));
        addmMap.put("isUpdate", map.get("isUpdate"));
        //发送添加根区域消息
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("OpType", "INSERT_OWN_CAMERA");
        jsonObject.put("Data", JSON.toJSONString(addmMap));
        MqttOp.publish(MediaMqConstants.CAMERA_TOPIC, JSON.toJSONString(jsonObject));
        return true;
    }

    private boolean insertOwnCamera(String data) {
        boolean isConsume = false;
        //海康返回的数据
        Map<String, String> objectMap = JSONObject.parseObject(data, new TypeReference<Map<String, String>>() {
        });
        //海康返回的设备数据
        List<RegionDeviceDto> hkCameraData = JSONObject.parseObject(objectMap.get("hkData"), new TypeReference<List<RegionDeviceDto>>() {
        });
        //区域信息
        List<DistrictFeignDto> districtFeignDTOList = JSONObject.parseObject(objectMap.get("area"), new TypeReference<List<DistrictFeignDto>>() {
        });
        //1. 获取海康设备唯一编码
        List<String> indexCodes = hkCameraData.stream().map(RegionDeviceDto::getIndexCode).collect(Collectors.toList());
        //2. 获取本系统已经同步设备编码
        List<CameraPlatform> selectList = hkSyncService.selectAllPlatformCode(1, 1);
        List<RegionDeviceDto> needUpdateDevice = new ArrayList<>();
        if (!selectList.isEmpty()) {
            //查询出本系统所有设备信息
            List<String> ownIndexCodes = selectList.stream().map(CameraPlatform::getPlatformCameraCode).collect(Collectors.toList());
            //去除已添加信息
            indexCodes.removeAll(ownIndexCodes);
            //获取三方已添加信息
            needUpdateDevice = hkCameraData.stream().filter(item -> ownIndexCodes.contains(item.getIndexCode())).collect(Collectors.toList());
        }
        //需要更新数据，去更新
        if (Boolean.parseBoolean(objectMap.get("isUpdate")) && !needUpdateDevice.isEmpty()) {
            List<String> ownSyncSuccessIndexCodes = needUpdateDevice.stream().map(RegionDeviceDto::getIndexCode).collect(Collectors.toList());
            //1. 查询设备数据
            Set<Integer> cameraIds = selectList.stream().map(item -> {
                        if (ownSyncSuccessIndexCodes.contains(item.getPlatformCameraCode())) {
                            return item.getOwnId();
                        } else {
                            return null;
                        }
                    }).filter(Objects::nonNull)
                    .collect(Collectors.toSet());
            List<CameraBase> cameraBaseList = hkSyncService.batchSelectByCameraIds(cameraIds);
            isConsume = updateCameraBase(cameraBaseList, needUpdateDevice);
        }
        //添加数据
        if (indexCodes.size() > 0) {
            //1. 收集所有需要添加的数据
            List<RegionDeviceDto> regionDeviceDtoList = hkCameraData
                    .stream()
                    .filter(item -> indexCodes.contains(item.getIndexCode()))
                    .collect(Collectors.toList());
            //2. 收集的数据转为自己数据库的数据
            List<CameraBase> cameraBaseList = convertData(regionDeviceDtoList, districtFeignDTOList);
            boolean isSuccess = hkSyncService.batchInsertCameraBase(cameraBaseList);
            //3. 转换数据为CameraPlatform集合
            List<CameraPlatform> cameraPlatformList = new ArrayList<>();
            if (isSuccess) {
                cameraPlatformList = convertCameraPlatform(cameraBaseList);
            }
            isConsume = hkSyncService.batchInsertCameraPlatform(cameraPlatformList);
        } else {
            //没有需要同步的数据直接返回true
            isConsume = true;
        }
        return isConsume;
    }

    /**
     * 同步设备时更新设备
     *
     * @param cameraBaseList   本系统设备信息
     * @param needUpdateDevice 三方系统设备信息
     * @return true
     */
    private boolean updateCameraBase(List<CameraBase> cameraBaseList, List<RegionDeviceDto> needUpdateDevice) {
        for (CameraBase cameraBase : cameraBaseList) {
            for (RegionDeviceDto deviceDto : needUpdateDevice) {
                if (cameraBase.getEncodeDevIndexCode().equals(deviceDto.getIndexCode())) {
                    cameraBase.setIp(deviceDto.getIp());
                    cameraBase.setPort(Integer.parseInt(deviceDto.getPort()));
                    cameraBase.setUserName(AesUtils.aesEnCode(deviceDto.getUserName()));
                }
            }
        }
        return hkSyncService.batchUpdateCameraBase(cameraBaseList);
    }

    private List<CameraBase> convertData(List<RegionDeviceDto> regionDeviceDtoList, List<DistrictFeignDto> districtFeignDTOList) {
        List<CameraBase> cameraBaseList = new ArrayList<>();
        for (RegionDeviceDto regionDeviceDTO : regionDeviceDtoList) {
            CameraBase cameraBase = new CameraBase();
            //设备名称
            cameraBase.setName(regionDeviceDTO.getName());
            //区域ID
            cameraBase.setDistrictId(findByregionIndexCode(districtFeignDTOList, regionDeviceDTO.getRegionIndexCode()));
            //设备编码
            cameraBase.setCode(UUID.fastUUID().toString());
            //接入协议
            if (EncodeDeviceProtocol.hiksdk_net.getProtocolName().equals(regionDeviceDTO.getTreatyType())) {
                cameraBase.setProtocolType(EncodeDeviceProtocol.hiksdk_net.getProtocol());
            } else if (EncodeDeviceProtocol.gb_reg.getProtocolName().equals(regionDeviceDTO.getTreatyType())) {
                cameraBase.setProtocolType(EncodeDeviceProtocol.gb_reg.getProtocol());
            }
            //ip地址
            cameraBase.setIp(regionDeviceDTO.getIp());
            //端口
            cameraBase.setPort(Integer.parseInt(regionDeviceDTO.getPort()));
            //设备账号
            cameraBase.setUserName(AesUtils.aesEnCode(regionDeviceDTO.getUserName()));
            //登录密码
            if (regionDeviceDTO.getPassword() != null) {
                cameraBase.setPassword(AesUtils.aesEnCode(regionDeviceDTO.getPassword()));
            }
            //设备厂商
            cameraBase.setCameraVendor(regionDeviceDTO.getManufacturer());
            //设备序列号
            cameraBase.setCameraSn(regionDeviceDTO.getDevSerialNum());
            //设备能力集
            cameraBase.setAbility(regionDeviceDTO.getCapability());
            //设备状态
            cameraBase.setStatus(1);
            //设备唯一编码
            cameraBase.setEncodeDevIndexCode(regionDeviceDTO.getIndexCode());
            //设别区域信息
            cameraBase.setRegionIndexCode(regionDeviceDTO.getRegionIndexCode());
            //加入集合
            cameraBaseList.add(cameraBase);
        }
        return cameraBaseList;
    }


    private Integer findByregionIndexCode(List<DistrictFeignDto> districtFeignDTOList, String regionIndexCode) {
        List<DistrictFeignDto> list = districtFeignDTOList
                .stream()
                .filter(item -> regionIndexCode.equals(item.getPlatformId()))
                .collect(Collectors.toList());
        if (list.size() > 0) {
            return list.get(0).getId();
        }
        return null;
    }


    private List<CameraPlatform> convertCameraPlatform(List<CameraBase> cameraBaseList) {
        List<CameraPlatform> cameraPlatformList = new ArrayList<>();
        for (CameraBase cameraBase : cameraBaseList) {
            CameraPlatform cameraPlatform = new CameraPlatform();
            //设备ID
            cameraPlatform.setOwnId(cameraBase.getId());
            //类型
            cameraPlatform.setType(1);
            //第三方平台
            cameraPlatform.setPlatformName("HK");
            //区域编码
            cameraPlatform.setPlatformDomainCode(cameraBase.getRegionIndexCode());
            //设备编码
            cameraPlatform.setPlatformCameraCode(cameraBase.getEncodeDevIndexCode());
            //设置状态
            cameraPlatform.setStatus(1);
            //第三方平台是否同步;1已同步 0未同步
            cameraPlatform.setIsSync(1);
            cameraPlatformList.add(cameraPlatform);
        }
        return cameraPlatformList;
    }


}

